// import { Stomp } from '@stomp/stompjs'
let socketOpen = false
let socketMsgQueue = []
let socketMsgSubscribe = {}

export default {
  client: null,
  timeout: 1000,
  baseURL: `wss://tragpt.xyz/user-ws`, //uni-app使用时不能使用http不然监听不到，需要使用ws

  init({ token, success, onClose }) {
    // if (this.client) {
    //   return Promise.resolve(this.client)
    // }
    // return new Promise((resolve, reject) => {
    // const ws = {
    //   send: null,
    //   onopen: null,
    //   onmessage: this.sendMessage,
    //   close: this.closeSocket
    // }

    let ws = new WebSocket(this.baseURL + '?token=' + token)
    ws.onopen = () => {
      console.log('WebSocket connected')
      socketOpen = true
      if (success) {
        success()
      }
    }
    ws.onmessage = (res) => {
      // const data = JSON.parse(res.data) // 解析接收到的消息数据
      console.log('WebSocket收到消息', res)
      const response = JSON.parse(res.data)
      Object.keys(socketMsgSubscribe).forEach((key) => {
        let item = socketMsgSubscribe[key]
        item.msgFun(response)
      })
      // this.messages.push(data) // 更新响应式数据以触发视图更新
    }
    ws.onerror = (error) => {
      console.error('WebSocket error:', error)
    }
    ws.onclose = (event) => {
      console.log('WebSocket closed:', event.reason)
      if (onClose) {
        onClose(event)
      }
    }
    this.client = ws

    // this.client.onMessage(function (res) {
    //   console.log('WebSocket收到消息', res)
    //   const response = JSON.parse(res.data)
    //   Object.keys(socketMsgSubscribe).forEach((key) => {
    //     let item = socketMsgSubscribe[key]
    //     console.log('item.type', item, response)
    //     item.msgFun(response)
    //   })
    // })
  },
  newSubscribe(id, type, msgFun) {
    socketMsgSubscribe[id] = { type, msgFun }
  },
  closeSubscribe(id) {
    delete socketMsgSubscribe[id]
  },
  disconnect() {
    this.client.close()
  },
  sendMessage(message) {
    if (socketOpen) {
      // uni.sendSocketMessage({
      //   data: message
      // })
      console.log('发送消息：', message)
      this.client.send(message)
    } else {
      socketMsgQueue.push(message)
    }
  },
  closeSocket(fun) {
    console.log('closeSocket')
    fun && fun()
  }
}
